const axios = require('axios');

class WechatAuthService {
  constructor() {
    this.appId = process.env.WECHAT_APPID;
    this.appSecret = process.env.WECHAT_APP_SECRET;
  }

  /**
   * 通过code获取openid和session_key
   * @param {string} code - 微信登录凭证
   * @returns {Promise<Object>} 包含openid和session_key的对象
   */
  async getOpenidByCode(code) {
    try {
      const url = 'https://api.weixin.qq.com/sns/jscode2session';
      const params = {
        appid: this.appId,
        secret: this.appSecret,
        js_code: code,
        grant_type: 'authorization_code'
      };

      const response = await axios.get(url, { params });
      
      if (response.data.errcode) {
        throw new Error(`微信API错误: ${response.data.errmsg}`);
      }

      return {
        success: true,
        data: {
          openid: response.data.openid,
          session_key: response.data.session_key,
          unionid: response.data.unionid
        }
      };

    } catch (error) {
      console.error('获取openid失败:', error);
      return {
        success: false,
        error: error.message || '获取openid失败'
      };
    }
  }

  /**
   * 解密微信用户信息
   * @param {string} encryptedData - 加密数据
   * @param {string} iv - 初始向量
   * @param {string} sessionKey - 会话密钥
   * @returns {Object} 解密后的用户信息
   */
  decryptUserInfo(encryptedData, iv, sessionKey) {
    const crypto = require('crypto');
    
    try {
      const sessionKeyBuffer = Buffer.from(sessionKey, 'base64');
      const encryptedDataBuffer = Buffer.from(encryptedData, 'base64');
      const ivBuffer = Buffer.from(iv, 'base64');
      
      const decipher = crypto.createDecipheriv('aes-128-cbc', sessionKeyBuffer, ivBuffer);
      decipher.setAutoPadding(true);
      
      let decrypted = decipher.update(encryptedDataBuffer, null, 'utf8');
      decrypted += decipher.final('utf8');
      
      return JSON.parse(decrypted);
    } catch (error) {
      console.error('解密用户信息失败:', error);
      throw new Error('解密失败');
    }
  }

  /**
   * 获取手机号（新版API）
   * @param {string} code - 手机号授权码
   * @returns {Promise<Object>} 包含手机号信息的对象
   */
  async getPhoneNumber(code) {
    try {
      // 首先获取access_token
      const accessToken = await this.getAccessToken();
      
      const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`;
      const response = await axios.post(url, {
        code
      });
      
      if (response.data.errcode && response.data.errcode !== 0) {
        throw new Error(`微信API错误: ${response.data.errmsg}`);
      }

      return {
        success: true,
        data: {
          phoneNumber: response.data.phone_info.phoneNumber,
          purePhoneNumber: response.data.phone_info.purePhoneNumber,
          countryCode: response.data.phone_info.countryCode,
          watermark: response.data.phone_info.watermark
        }
      };

    } catch (error) {
      console.error('获取手机号失败:', error);
      return {
        success: false,
        error: error.message || '获取手机号失败'
      };
    }
  }

  /**
   * 获取微信access_token
   * @returns {Promise<string>} access_token
   */
  async getAccessToken() {
    try {
      const url = 'https://api.weixin.qq.com/cgi-bin/token';
      const params = {
        grant_type: 'client_credential',
        appid: this.appId,
        secret: this.appSecret
      };

      const response = await axios.get(url, { params });
      
      if (response.data.errcode) {
        throw new Error(`获取access_token失败: ${response.data.errmsg}`);
      }

      return response.data.access_token;
    } catch (error) {
      console.error('获取access_token失败:', error);
      throw error;
    }
  }
}

module.exports = new WechatAuthService();